<template>
  <el-row>
    <!-- 李康编写，邓夏伍迁移 -->
    <el-form :model="model" label-position="left" ref="elForm" label-width="140px">
      <!--新增 (无id: 头部表单：-->
      <Portlet title="新增账号">
        <el-row :gutter="15">
          <el-col :md="12" :lg="8" :xl="6">
            <el-form-item label="登陆账号：" prop="loginName" :rules="[
              { required: true, message: '请输入账号', trigger: 'blur' },
              { validator: isEnglishOrNumber, message: '账号只能是字母或数字', trigger: 'blur' }
            ]">
              <span v-if="isEdit">{{ model.loginName }}</span>
              <el-input v-else v-model="model.loginName">
                <template slot="prepend">{{ model.companyCode }}-</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="8" :xl="6">
            <el-form-item label="姓名：" prop="name" :rules="[
              {required: true, message: '姓名必须', trigger: 'blur'}
            ]">
              <el-input v-model="model.name"></el-input>
            </el-form-item>
          </el-col>

          <el-col :md="12" :lg="8" :xl="6">
            <el-form-item label="岗位：">
              <el-input v-model="model.position"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </Portlet>
      <!--下半截 角色 + 菜单 -->
      <el-row v-for="(item, index) in model.roleIdList" :key="index">
        <RoleMenu :isInsert="1" @delRole="delRole" @addRole="addRole" :projectType="projectType"
                  :itemArr.sync="model.roleIdList" :index="index" :item="item"></RoleMenu>
      </el-row>
      <!--按钮-->
      <el-row>
        <Portlet>
          <el-row>
            <el-col :span="24" class="text-center">
              <el-button class="btn-block" type="primary"
                         :loading="submitLoading" @click.prevent="submit">{{ isEdit ? '保存' : '新增' }}</el-button>
            </el-col>
          </el-row>
        </Portlet>
      </el-row>
    </el-form>
  </el-row>
</template>

<script>
import {copy, dotData, confirm} from '@/utils'
import RoleMenu from '@/views/fhb/account/RoleMenu'
import {isEnglishOrNumber} from '@/utils/validate'
import {getUserInfo} from '@/utils/auth'
export default {
  components: {
    RoleMenu
  },
  props: {
    projectType: {
      type: String,
      default: process.env.projectType
    }
  },
  created() {
    if (this.id) {
      this.getDetail()
    } else {
      this.model.roleIdList = [{roleId: ''}]
    }
    this.isPassCompanyAuthentication()
  },
  data() {
    return {
      id: this.$route.params.id,
      routeName: this.$route.name,
      submitLoading: false,
      model: {
        name: '',
        loginName: '',
        position: '',
        roleIdList: [],
        authSystem: this.projectType,
        companyCode: ''
      },
      defaultPassword: '123456',
      credentialDetail: {}
    }
  },
  computed: {
    // 是否是新增编辑页
    isEdit() {
      return !!this.id
    }
  },
  methods: {
    isEnglishOrNumber,
    // 新增 提交
    // 获取发货宝是否通过公司认证
    isPassCompanyAuthentication() {
      this.$ajax.get('/ms-fahuobao-user/OutGoodsUser/is-mentCredential', {userId: getUserInfo('id')}).then(response => {
        if (response.success) {
          this.credentialDetail = response.data || {}
          // 获取公司编号
          this.model.companyCode = dotData(response, 'data.companyCode') || ''
        }
      })
    },
    submit() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          return
        }
        let data = copy(this.model, true)
        let url = ''
        if (this.isEdit) {
          url = '/ms-common-user/user/updateUser'
          data.userId = this.id
        } else {
          url = '/ms-common-user/childUser/saveChildUser'
          data.pwd = this.defaultPassword
        }
        this.submitLoading = true
        data.roleIdList = data.roleIdList.map(v => v.roleId)
        this.$ajax.post(url, data).then(response => {
          const success = response.success
          if (success) {
            confirm(this.isEdit ? '保存成功' : '新增成功', '提示', {
              type: success,
              showCancelButton: false
            }).then(_ => {
              this.$router.push({path: '/redirect/ss-fhb/account/index'})
            })
          }
        }).finally(_ => {
          this.submitLoading = false
        })
      })
    },
    // 修改时 请求roleId名+权限id 并 回填 下半截：
    getDetail() {
      this.$ajax.get('/ms-common-user/user/getUserAllDetails', {userId: this.id, projectType: this.projectType}).then(response => {
        if (dotData(response, 'success')) {
          // 回填 this.model.orderIds
          this.model.name = dotData(response, 'data.orgUser.name') || ''
          this.model.loginName = dotData(response, 'data.orgUser.loginName') || ''
          this.model.pwd = dotData(response, 'data.orgUser.pwd') || ''
          this.model.position = dotData(response, 'data.orgUser.position') || ''
          let backOrderIds = dotData(response, 'data.roleExtBeans') || []
          if (Array.isArray(backOrderIds)) {
            this.model.roleIdList = backOrderIds.map(v => {
              return {roleId: v.id}
            })
            console.log(this.model.roleIdList, 'this.model.roleIdList')
          }
        }
      }).finally(_ => {
        if (this.model.roleIdList.length === 0) {
          this.model.roleIdList = [{
            roleId: ''
          }]
        }
      })
    },
    delRole(index) {
      this.model.roleIdList.splice(index, 1)
    },
    addRole() {
      this.model.roleIdList.push({
        roleId: ''
      })
    }
  }
}
</script>
